const mongo_client = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const db_name = 'priKey-acct';

const db_operate = (cb) => {
    mongo_client.connect(url, (err, client) => {
        if (err) {
            console.log(err);
        }
        const db =client.db(db_name);
        cb(db);
    })
}

const insert_pk = (db, obj, cb) => {
    const collection = db.collection('user');
    collection.insertOne({
        acct: obj.acct,
        priKey: obj.priKey,
    }, (result) => {
        cb();
    })
}

class PkManageModule{
    constructor(obj) {
        for (let key in obj) {
            this[key] = obj[key];
        }
    }

    save(cb){
        db_operate((db) => {
            insert_pk(db, {
                acct: this.acct,
                priKey: this.priKey,
            }, () => {
                console.log('priKey storaged');
                cb();
            })
        })
    }

    static get_user_by_priKey(pk, cb) {
        db_operate((db) => {
            const collection = db.collection('user');
            collection.find({ 'priKey': pk }).toArray((err, result) => {
                if (err) {
                    console.log(err);
                    cb(err);
                } else {
                    const user = result[0];
                    cb(user);
                }
            })
        })
    }

    static get_priKey_by_user(acct, cb) {
        db_operate((db) => {
            const collection = db.collection('user');
            collection.find({ 'acct': acct }).toArray((err, result) => {
                if (err) {
                    console.log(err);
                    cb(err);
                } else {
                    const user = result[0];
                    console.log(user);
                    cb(user);
                }
            })
        })
    }

    static authenticate(pk, cb) {
        PkManageModule.get_user_by_acct(pk, (result) => {
            if (typeof(result) !== 'undefined') { // 用户存在
                let state = false;
                cb(state);
            } else {
                let state = true;
                cb(state);
            }
        })
    }

}
module.exports = PkManageModule;